
package com.ruoyi.web.controller.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@ServerEndpoint(value = "/ws/{userId}")
@Component
@CrossOrigin
public class WebSocketServer {
    private static final Logger logger = LoggerFactory.getLogger("ws-link");
    private static AtomicInteger count = new AtomicInteger(0);//记录在线用户
    private static ConcurrentHashMap<String, WebSocketServer> links = new ConcurrentHashMap<>();

    private Session session;
    private String userId;

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        logger.info("用户：" + userId + "开始连接");
        this.session = session;
        this.userId = userId;
        if (links.containsKey(userId)) {
            links.remove(userId);
            links.put(userId, this);
        } else {
            links.put(userId, this);
            count.incrementAndGet();
        }
        logger.info("当前在线人数：" + count.get());
    }
/**
     * 连接关闭调用的方法
     */

    @OnClose
    public void onClose() {
        logger.info("用户：" + userId + "断开连接");
        if (links.containsKey(userId)) {
            links.remove(userId);
            count.decrementAndGet();
        }
        logger.info("当前在线人数：" + count.get());
    }


/**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */

    @OnMessage
    public void onMessage(String message, Session session) {
        this.sendMessage(message, session);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }


/**
     * 服务端发送消息给客户端
     */

    private void sendMessage(String message, Session toSession) {
        try {
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
        }
    }

    public static  void sendMessage(String msg,Long userId) {
        Session session = links.get(userId).session;
        try {
            session.getBasicRemote().sendText(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

